package multithread.framework.tool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * XML generator
 * 
 * @author dailey_dai
 * 
 */
public class XMLGenerator implements IGenerator<File, Document> {
	private Document document = null;
	private File outputfile = null;
	private Format format = null;
	private OutputStream out = null;

	public XMLGenerator(File file) {
		this(file, Format.getPrettyFormat());
	}

	public XMLGenerator(String generatePath) {
		this(new File(generatePath), Format.getPrettyFormat());
	}

	public XMLGenerator(File file, Format format) {
		this.outputfile = file;
		this.format = format;
		document = new Document();
	}

	/**
	 * redirect output XML content to other stream
	 * 
	 * @param out
	 *            OutputStream
	 * @return XMLGenerator
	 */
	public static XMLGenerator getSpecialInstance(OutputStream out) {
		return new XMLGenerator(out);
	}

	private XMLGenerator(OutputStream out) {
		this(out, Format.getPrettyFormat());
	}

	private XMLGenerator(OutputStream out, Format format) {
		this.out = out;
		this.format = format;
		document = new Document();
	}

	public void setOutputfile(File outputfile) {
		this.outputfile = outputfile;
	}

	public void setFormat(Format format) {
		this.format = format;
	}

	protected Document getDocument() {
		return document;
	}

	/**
	 * write a document to generate XML
	 */
	@Override
	public void write(Document doc) {
		this.document = doc;
	}

	/**
	 * generate a XML file
	 * 
	 * @return File
	 */
	@Override
	public File generate() {
		XMLOutputter xmloutter = new XMLOutputter();

		if (format != null)
			xmloutter.setFormat(format);
		try {
			if (document != null) {
				if (out == null) {
					if (outputfile == null)
						throw new IllegalArgumentException(
								"outputfile can not be null.");
					if (!outputfile.exists())
						outputfile.createNewFile();
					out = new FileOutputStream(outputfile);
				}
				xmloutter.output(document, out);
			}
			if (out != null) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return outputfile;
	}

}
